import Vue from 'vue'
import VueRouter from 'vue-router'
// vueX
import store from '@/store'
Vue.use(VueRouter)
// 定义路由规则
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: () => import('@/login.vue') },
  { path: '/reg', component: () => import('@/register.vue') },
  {
    path: '/main',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/main/home',
    children: [
      { path: 'home', component: () => import('@/views/home/index.vue') },
      {
        path: 'user-info',
        component: () => import('@/views/user/userInfo.vue'),
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar.vue'),
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd.vue'),
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCate.vue'),
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList.vue'),
      },
    ],
  },
]

const router = new VueRouter({
  routes,
})
// 全局前置路由守卫
// 知识点1:浏览器第一次打开项目页面，会触发一次全局前置路由守卫函数
// 知识点2:判断登录与否:有token就证明登录了，无token就是未登录
// 知识点3:next()如果强制切换路由地址，会再次走路由守卫函数再次去匹配路由表

const whitelist = ['/login', '/reg'] // 白名单 没有token值照样能看见其页面

// 如果用户未登录 则只展示登录页面和注册页面 其余什么页面都不显示
router.beforeEach((to, from, next) => {
  const token = store.state.token
  // 如果没有token值 且要去往的地址不在白名单里 则强制跳转到登录页面
  if (!token && !whitelist.includes(to.path)) {
    next('/login')
  } else {
    next()
  }
  if (to.path === '/login' || to.path === '/reg') {
    store.commit('updateToken', '')
    store.commit('updateUserInfo', '')
    store.commit('updateUserPwd', '')
  }
})

export default router
